import Cocoa
import os.log

class FloatingWindow: NSWindow {
    private var imageView: NSImageView
    private var originalSize: NSSize
    private var isMinimized = false
    private let logger = OSLog(subsystem: "com.macscreenshot", category: "FloatingWindow")
    private var eventMonitor: Any?
    
    init(image: NSImage, origin: NSPoint) {
        os_log("Initializing FloatingWindow with image size: %{public}@", log: logger, type: .info, String(describing: image.size))
        self.originalSize = image.size
        
        // 创建图片视图
        self.imageView = NSImageView(frame: NSRect(origin: .zero, size: image.size))
        self.imageView.image = image
        self.imageView.imageScaling = .scaleProportionallyUpOrDown
        
        // 创建窗口
        super.init(
            contentRect: NSRect(origin: origin, size: image.size),
            styleMask: [.borderless, .resizable],
            backing: .buffered,
            defer: false
        )
        
        os_log("Window initialized with frame: %{public}@", log: logger, type: .info, String(describing: frame))
        
        // 配置窗口
        self.isReleasedWhenClosed = false
        self.backgroundColor = .clear
        self.level = .floating
        self.collectionBehavior = [.canJoinAllSpaces, .participatesInCycle, .fullScreenAuxiliary]
        self.isMovableByWindowBackground = true
        self.hasShadow = true
        
        // 设置内容视图
        if let contentView = self.contentView {
            contentView.wantsLayer = true
            contentView.layer?.backgroundColor = NSColor.windowBackgroundColor.cgColor
            contentView.layer?.cornerRadius = 8
            contentView.layer?.masksToBounds = true
            
            // 添加图片视图
            contentView.addSubview(imageView)
            imageView.frame = contentView.bounds
            imageView.autoresizingMask = [.width, .height]
            
            os_log("Content view setup complete", log: logger, type: .info)
        } else {
            os_log("Failed to get content view", log: logger, type: .error)
        }
        
        // 注册双击事件
        let clickGesture = NSClickGestureRecognizer(target: self, action: #selector(handleDoubleClick(_:)))
        clickGesture.numberOfClicksRequired = 2
        imageView.addGestureRecognizer(clickGesture)
        
        // 监听ESC键
        eventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
            if event.keyCode == 53 { // ESC key
                self?.close()
                return nil
            }
            return event
        }
        
        // 监听窗口激活状态
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(windowDidBecomeKey(_:)),
            name: NSWindow.didBecomeKeyNotification,
            object: self
        )
    }
    
    @objc private func handleDoubleClick(_ gesture: NSClickGestureRecognizer) {
        if isMinimized {
            // 恢复原始大小
            self.setFrame(NSRect(origin: frame.origin, size: originalSize), display: true, animate: true)
        } else {
            // 缩小到100x100
            let minimizedSize = NSSize(width: 100, height: 100)
            self.setFrame(NSRect(origin: frame.origin, size: minimizedSize), display: true, animate: true)
        }
        isMinimized = !isMinimized
    }
    
    @objc private func windowDidBecomeKey(_ notification: Notification) {
        // 确保窗口始终保持在顶层
        self.level = .floating
    }
    
    override func close() {
        if let monitor = eventMonitor {
            NSEvent.removeMonitor(monitor)
            eventMonitor = nil
        }
        NotificationCenter.default.removeObserver(self)
        super.close()
    }
    
    deinit {
        os_log("FloatingWindow being deallocated", log: logger, type: .info)
    }
}
